package com.greateamd.timetableasy.server.services;

import org.apache.log4j.Logger;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import com.greateamd.timetableasy.client.services.login.LoginService;
import com.greateamd.timetableasy.domain.User;
import com.greateamd.timetableasy.domain.exceptions.DBServerSideException;
import com.greateamd.timetableasy.domain.exceptions.ServerSideException;
import com.greateamd.timetableasy.server.dao.UserDAO;

@Service("loginService")
public class LoginServiceImpl implements LoginService {

	Logger log = Logger.getLogger(this.getClass());

	private UserDAO userDAO;
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}
	/**
	 * Inject the authentication manager specified in app-springsecurity-context.xml
	 */
	ProviderManager authenticationManager;
	public void setAuthenticationManager(ProviderManager authenticationManager){
		this.authenticationManager = authenticationManager;
	}

	@Override
	public String login(String username, String password) throws ServerSideException {

		log.debug("Authentication attempt: " + username + " " + password);
		Authentication result = null;
	    try {
	        Authentication request = new UsernamePasswordAuthenticationToken(username, password);
	        result = authenticationManager.authenticate(request);
	        SecurityContextHolder.getContext().setAuthentication(result);
	    } catch (AuthenticationException e) {
	    	log.info("Authentication failed: " + e.getMessage());
	        return null;
	    }
	    log.info("Authentication success: " + SecurityContextHolder.getContext().getAuthentication());
	    if(result==null){
	    	return null;
	    }
	    return result.getName();
	}

	@Override
	public User getUser() throws ServerSideException {
		try {
			User currentUser = null;
			
			if(SecurityContextHolder.getContext().getAuthentication().getName() != null ){
				currentUser = userDAO.getById(SecurityContextHolder.getContext().getAuthentication().getName());
			}
			return currentUser;
		} catch (Exception e) {
			throw new DBServerSideException(e.getMessage());
		}
	}

	
}
